package com.asking.controller;

import com.asking.domain.Question;
import com.asking.pojo.EsQuestion;
import com.asking.service.QuestionService;
import com.asking.vo.Result;
import com.asking.vo.ResultVo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Author: 宋定鑫
 * @Date: 2018/10/17 20:13
 */
@RestController
@RequestMapping("/question")
public class QuestionController {

    @Resource
    private QuestionService questionService;

    /**
     * 添加问题
     * @param question
     * @return
     */
    @PostMapping("/add")
    public ResponseEntity<Result> add(Question question){
        try{
            questionService.add(question);
            return new ResponseEntity<>(new Result(200,"问题新增成功"), HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity<>(new Result(500,"问题新增失败"),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 更新问题
     * @param question
     * @return
     */
    @PutMapping
    public ResponseEntity<Result> updatquestion(Question question){
        try{
            questionService.updata(question);
            return new ResponseEntity<>(new Result(204,"问题修改成功"), HttpStatus.NO_CONTENT);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity<>(new Result(500,"问题修改失败"),HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 根据id查询问题
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ResponseEntity<Result> idquestion(@PathVariable("id")Integer id){
        try {
            EsQuestion question =questionService.selectByAnswer(id);
            return new ResponseEntity<>(new Result(200,"",question),HttpStatus.OK);
        }catch (Exception e){
            return new ResponseEntity<>(new Result(500,""),HttpStatus.INTERNAL_SERVER_ERROR);

        }

    }

    /**
     * 查询所有并搜索
     * @param page
     * @param rows
     * @param title
     * @return
     */
    @GetMapping("/findAll")
    public ResponseEntity<Result> findAll(Integer page,Integer rows,String  title){
        try {
            ResultVo all = questionService.findAll(page,rows,title);
            return new ResponseEntity<>(new Result(200,"",all),HttpStatus.OK);
        }catch (Exception e){
            return new ResponseEntity<>(new Result(500,""),HttpStatus.INTERNAL_SERVER_ERROR);

        }

    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Result> deleteidquestion(@PathVariable("id")Integer id){
        try{
            questionService.deleteidquestion(id);
            return new ResponseEntity<>(new Result(204,"问题删除成功"),HttpStatus.NO_CONTENT);
        }catch(Exception e){
            e.printStackTrace();
            return new ResponseEntity<>(new Result(500,"问题删除失败"),HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

}
